package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;

public class EmployeeRealm extends AuthorizingRealm {
    @Setter
    private IEmployeeService empService;
    @Setter
    private IRoleService roleService;
    @Setter
    private IPermissionService permissionService;

    public String getName() {
        return "EmployeeRealm";
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取当前登录用户
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        List<String> roles = null;
        List<String> permissions = null;
        if (employee.isAdmin()) {
            roles = new ArrayList<>();
            //超级管理员拥有所有角色
            List<Role> list = roleService.list();
            for (Role role : list) {
                roles.add(role.getSn());
            }
            //超级管理员拥有所有权限
            permissions = new ArrayList<>();
            permissions.add("*:*");
        } else {
            //非超级管理员
            //查询当前用户的角色
            roles = roleService.getRoleSnByEmpId(employee.getId());
            //查询当前用户的权限
            permissions = permissionService.getPermissionResourceByEmpId(employee.getId());

        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;

    }

    //验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取当前页面传入的用户名
        String username = (String) token.getPrincipal();
        Employee employee = empService.validateUsername(username);
        if (employee == null) {
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee, employee.getPassword(), getName());
        return info;
    }
}
